<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="运单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入运单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="快递状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="请选择审核状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未处理" :value="0"/>
          <el-option label="已出单" :value="1"/>
          <el-option label="已取消" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="auditDatetime">
        <el-date-picker
          v-model="queryParams.auditDatetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="收件国家" prop="country">
        <el-select
          v-model="queryParams.country"
          placeholder="请选择收件国家"
          clearable
          class="!w-240px"
        >
          <el-option label="韩国" value="韩国"/>
          <el-option label="美国" value="美国"/>
          <el-option label="孟加拉" value="孟加拉"/>
          <el-option label="缅甸" value="缅甸"/>
          <el-option label="柬埔寨" value="柬埔寨"/>
          <el-option label="越南" value="越南"/>
          <el-option label="印度尼西亚" value="印度尼西亚"/>
          <el-option label="其他" value="其他"/>
        </el-select>
      </el-form-item>
      <el-form-item label="运输方式" prop="shippingType">
        <el-select
          v-model="queryParams.shippingType"
          placeholder="请选择运输方式"
          clearable
          class="!w-240px"
        >
          <el-option v-if="queryParams.country != '缅甸' && queryParams.country != '柬埔寨'"
                     label="空运" value="空运"/>
          <el-option
            v-if="queryParams.country === '缅甸' || queryParams.country === '柬埔寨' || queryParams.country === '越南'"
            label="陆运" value="陆运"/>
          <el-option v-if="queryParams.country === '韩国' || queryParams.country === '其它'"
                     label="海运" value="海运"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否报关" prop="customsFiling">
        <el-select
          v-model="queryParams.customsFiling"
          placeholder="请选择是否报关"
          clearable
          class="!w-240px"
        >
          <el-option label="否" :value="0"/>
          <el-option label="是" :value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="寄件方公司抬头" label-width="110px" prop="sendCompany">
        <el-input
          v-model="queryParams.sendCompany"
          placeholder="请输入寄件方公司抬头"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="收件方公司抬头" label-width="110px" prop="recipientsCompany">
        <el-input
          v-model="queryParams.recipientsCompany"
          placeholder="请输入收件方公司抬头"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="结款方式" prop="payMethod">
        <el-select
          v-model="queryParams.payMethod"
          placeholder="请选择结款方式"
          clearable
          class="!w-240px"
        >
          <el-option label="寄付" :value="0"/>
          <el-option label="到付" :value="1"/>
          <el-option label="第三方结款" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="客户账号" prop="customerAccount">
        <el-input
          v-model="queryParams.customerAccount"
          placeholder="请输入客户账号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="快递单号" prop="expressageOrder">
        <el-input
          v-model="queryParams.expressageOrder"
          placeholder="请输入快递单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
<!--        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['business:expressage:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>-->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['business:expressage:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
        <el-button @click="downloadFile(1)" :disabled="downloadPdfWaybill" type="primary">下载Pdf面单</el-button>
        <el-button @click="downloadFile(2)" :disabled="downloadPdfInvoice" type="success">下载Pdf发票</el-button>
        <el-button @click="downloadFile(3)" :disabled="downloadExcelInvoice" type="success">下载Excel发票</el-button>
        <!--        <el-button
                  type="danger"
                  plain
                  :disabled="isEmpty(checkedIds)"
                  @click="handleDeleteBatch"
                  v-hasPermi="['business:expressage:delete']"
                >
                  <Icon icon="ep:delete" class="mr-5px"/>
                  批量删除
                </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" :selectable="selectableRow"/>
      <el-table-column min-width="140" label="运单号" align="center" prop="orderNo"/>
      <el-table-column min-width="170" label="下单时间" align="center" prop="createTime"/>
      <el-table-column min-width="100" label="快递状态" align="center" prop="auditStatus">
        <template #default="{ row }">
          <el-tag type="danger" v-if="row.auditStatus === 0">未处理</el-tag>
          <el-tag type="success" v-else-if="row.auditStatus === 1">已出单</el-tag>
          <el-tag type="info" v-else>已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column min-width="100" label="下单人ID" align="center" prop="userId"/>
      <el-table-column min-width="140" label="昵称" align="center" prop="nickname"/>
      <el-table-column min-width="140" label="手机号" align="center" prop="mobile"/>
      <el-table-column min-width="100" label="收件国家" align="center" prop="country"/>
      <el-table-column min-width="100" label="运输方式" align="center" prop="shippingType"/>
      <el-table-column min-width="100" label="是否报关" align="center" prop="customsFiling">
        <template #default="{ row }">
          <el-tag v-if="row.customsFiling">报关</el-tag>
          <el-tag type="info" v-else>不报关</el-tag>
        </template>
      </el-table-column>
      <el-table-column min-width="170" label="寄件方公司抬头" align="center" prop="sendCompany"/>
      <el-table-column min-width="170" label="收件方公司抬头" align="center" prop="recipientsCompany"/>
      <el-table-column min-width="100" label="结款方式" align="center" prop="payMethod">
        <template #default="{ row }">
          <el-tag v-if="row.payMethod === 0">寄付</el-tag>
          <el-tag type="warning" v-else-if="row.payMethod === 1">到付</el-tag>
          <el-tag type="success" v-else>第三方结款</el-tag>
        </template>
      </el-table-column>
      <el-table-column min-width="140" label="客户账号" align="center" prop="customerAccount"/>
      <el-table-column min-width="140" label="快递单号" align="center" prop="expressageOrder"/>
<!--      <el-table-column
        label="审核时间"
        align="center"
        prop="auditDatetime"
        :formatter="dateFormatter"
        width="180px"
      />-->
      <el-table-column fixed="right" label="操作" align="center" min-width="200px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm(scope.row.id)"
            v-hasPermi="['business:expressage:update']"
          >
             {{scope.row.auditStatus === 0 ? '审核' : '查看'}}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:expressage:delete']"
          >
            删除
          </el-button>
          <el-dropdown
            v-if="scope.row.auditStatus === 1"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['business:expressage:query']"
          >
            <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="downloadPdfWaybill"
                  v-if="checkPermi(['business:expressage:query'])"
                >
                  <Icon icon="ep:download" />下载pdf面单
                </el-dropdown-item>
                <el-dropdown-item
                  command="downloadPdfInvoice"
                  v-if="checkPermi(['business:expressage:query'])"
                >
                  <Icon icon="ep:download" />下载pdf发票
                </el-dropdown-item>
                <el-dropdown-item
                  command="downloadExcelInvoice"
                  v-if="checkPermi(['business:expressage:query'])"
                >
                  <Icon icon="ep:download" />下载excel发票
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
<!--  <ExpressageForm ref="formRef" @success="getList"/>-->
</template>

<script setup lang="ts">
import {isEmpty} from '@/utils/is'
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {ExpressageApi, Expressage} from '@/api/business/expressage'
import ExpressageForm from './form/index.vue'
import {checkPermi} from "@/utils/permission";
import * as UserApi from "@/api/system/user";
import {useRoute, useRouter} from "vue-router";
import {array} from "vue-types";

/** 寄件信息 列表 */
defineOptions({name: 'Expressage'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const route = useRoute() // 路由
const router = useRouter() // 路由

const loading = ref(true) // 列表的加载中
const list = ref<Expressage[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderNo: undefined,
  nickname: undefined,
  mobile: undefined,
  userId: undefined,
  country: undefined,
  shippingType: undefined,
  customsFiling: undefined,
  sendName: undefined,
  sendMobile: undefined,
  sendAddress: undefined,
  sendCompany: undefined,
  sendDept: undefined,
  recipientsName: undefined,
  recipientsMobile: undefined,
  recipientsAddress: undefined,
  recipientsCompany: undefined,
  recipientsDept: undefined,
  payMethod: undefined,
  customerAccount: undefined,
  invoiceNum: undefined,
  expressageOrder: undefined,
  auditStatus: undefined,
  auditDatetime: [],
  auditAdminUserId: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 下载面单 */
const downloadFile = async (type: number) => {
  try {
    switch (type) {
      case 1:
        downloadPdfWaybill.value = true;
        break
      case 2:
        downloadPdfInvoice.value = true;
        break
      case 3:
        downloadExcelInvoice.value = true;
        break
      default:
        break
    }

    let fileUrl = await ExpressageApi.downloadExpressage(type, {ids: checkedIds.value})
    const a = document.createElement('a')
    a.href = fileUrl
    a.click()
  }finally {
    downloadPdfWaybill.value = false;
    downloadPdfInvoice.value = false;
    downloadExcelInvoice.value = false;
  }
}

let downloadPdfWaybill = ref(false)
let downloadPdfInvoice = ref(false)
let downloadExcelInvoice = ref(false)

/** 操作分发 */
const handleCommand = async (command: string, row: ExpressageApi.Expressage) => {
  try {
    let type = undefined;
    switch (command) {
      case 'downloadPdfWaybill':
        type = 1;
        downloadPdfWaybill.value = true;
        break
      case 'downloadPdfInvoice':
        type = 2;
        downloadPdfInvoice.value = true;
        break
      case 'downloadExcelInvoice':
        type = 3;
        downloadExcelInvoice.value = true;
        break
      default:
        break
    }

    let fileUrl = await ExpressageApi.downloadExpressage(type, {ids: [row.id]})
    const a = document.createElement('a')
    a.href = fileUrl
    a.download = row.orderNo + '.xlsx'
    a.click()
  }finally {
    downloadPdfWaybill.value = false;
    downloadPdfInvoice.value = false;
    downloadExcelInvoice.value = false;
  }
}

/** 查询列表 */
const selectableRow = (row) => {
  return row.auditStatus === 1
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ExpressageApi.getExpressagePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (id?: number) => {
  router.push({
    name: 'ExpressageForm',
    query: { id: id }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ExpressageApi.deleteExpressage(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 批量删除寄件信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ExpressageApi.deleteExpressageList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Expressage[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ExpressageApi.exportExpressage(queryParams)
    download.excel(data, '寄件信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
